package com.ruoyi.app.activity

import ViewPagerAdapter
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.core.content.ContextCompat
import androidx.viewpager2.widget.ViewPager2
import com.bumptech.glide.Glide
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayoutMediator
import com.ruoyi.app.R
import com.ruoyi.app.activity.common.WebActivity
import com.ruoyi.app.api.ConfigApi
import com.ruoyi.app.databinding.ActivityLoginBinding
import com.ruoyi.app.model.Constant
import com.ruoyi.app.model.UserViewModel
import com.ruoyi.code.Frame
import com.ruoyi.code.base.BaseBindingActivity
import com.ruoyi.code.base.activityViewModels
import com.ruoyi.code.base.viewbinding.binding
import com.ruoyi.code.utils.clickDelay
import com.ruoyi.code.witget.toast
import com.tencent.mmkv.MMKV
import com.therouter.TheRouter
import com.xuexiang.xupdate.XUpdate


class LoginActivity : BaseBindingActivity<ActivityLoginBinding>() {

    companion object {
        fun startActivity(context: Context) {
            val intent = Intent(context, LoginActivity::class.java)
            if (context !is Activity) {
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            }
            context.startActivity(intent)
        }
    }

    private val viewModel: UserViewModel by activityViewModels()

    override fun initView() {
        val viewPager = findViewById<ViewPager2>(R.id.viewPager)
        val tabLayout = findViewById<TabLayout>(R.id.tabLayout)
        // 设置适配器
        viewPager.adapter = ViewPagerAdapter(this)

        // 绑定 TabLayout 和 ViewPager2
        TabLayoutMediator(tabLayout, viewPager) { tab, position ->
            tab.text = when (position) {
                0 -> "账号密码登录"
                1 -> "手机号登录"
                else -> ""
            }
        }.attach()

        val token = MMKV.defaultMMKV().decodeString("token")
        if (!token.isNullOrEmpty()) {
            TheRouter.build(Constant.mainRoute)
                .navigation()
            finish()
            return
        } else {
            XUpdate.newBuild(this)
                .promptThemeColor(ContextCompat.getColor(this, R.color.red))
                .updateUrl(ConfigApi.uploadApp)
                .update()
        }

    }

    override fun initData() {
        viewModel.getVerificationCode()
        viewModel.errorMsg.observe(this) {
            toast(it)
        }
        viewModel.loginSuceess.observe(this) {
            TheRouter.build(Constant.mainRoute)
                .navigation()
            finish()
        }
    }

}
